//
//  TaijieBiVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/4/20.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "TaijieBiVC.h"
#import "InAppRageIAPHelper.h"
#import "TaijieBiTableViewCell.h"
#import "NSUDManager.h"

@interface TaijieBiVC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;
@property (strong, nonatomic) IBOutlet UIView *footerView;
@property (weak, nonatomic) IBOutlet UILabel *totalTaijieLabel;

@end

@implementation TaijieBiVC
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kProductsLoadedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kProductPurchasedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kProductPurchaseFailedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kProductRePurchaseFailedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"我的台阶币";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productsLoaded:) name:kProductsLoadedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:kProductPurchasedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(productPurchaseFailed:) name:kProductPurchaseFailedNotification object: nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(reProductPurchaseFailed) name:kProductRePurchaseFailedNotification object: nil];
    
    [self loadTabbleView];
    
//    if ([InAppRageIAPHelper sharedHelper].products == nil) {
//
        [[InAppRageIAPHelper sharedHelper] requestProducts];
//        [self showProgressWithView:self.view animated:YES];
//        [self performSelector:@selector(timeout:) withObject:nil afterDelay:30.0];
//
//    }else{
//        [[InAppRageIAPHelper sharedHelper] requestProducts];
//        [self showProgressWithView:self.view animated:YES];
//        [self performSelector:@selector(timeout:) withObject:nil afterDelay:30.0];
//        //            [self.buyTableVIew reloadData];
//    }
    
    [self walletMoney];
    
    self.arrData = [NSMutableArray array];
    [self.arrData addObject:@{@"name":@"4",@"price":@"6",@"id":@"com.taijie.6"}];
    [self.arrData addObject:@{@"name":@"12",@"price":@"18",@"id":@"com.taijie.18"}];
    [self.arrData addObject:@{@"name":@"30",@"price":@"45",@"id":@"com.taijie.45"}];
    [self.arrData addObject:@{@"name":@"74",@"price":@"108",@"id":@"com.taijie.108"}];
    [self.arrData addObject:@{@"name":@"225",@"price":@"328",@"id":@"com.taijie.328"}];
    [self.arrData addObject:@{@"name":@"478",@"price":@"698",@"id":@"com.taijie.698"}];
    
}
-(void)walletMoney{
    UserModel *user = [NSUDManager currentUser];
    [YJMSendRequest postDataWithParameters:@{@"userId":user.userId} url:@"user/getIncumbentInfo" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            self.totalTaijieLabel.text = [NSString stringWithFormat:@"%@台阶币",result[@"data"][@"userInfo"][@"leftToken"]];
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
    
}
-(void)reProductPurchaseFailed{
    [self hideProgress:self.view animated:YES];
    [CommonUtils showToast:@"该Apple id未检测到购买记录，请联系管理员:15140440269@163.com"];

}
- (void)productsLoaded:(NSNotification *)notification {
    
    
//    SaintiLog(@"-----交易完成 --------");
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
//    [self hideProgress:self.view animated:YES];
//    self.arrData = [NSMutableArray arrayWithArray:[InAppRageIAPHelper sharedHelper].products];
//    for (int i = 0; i < self.arrData.count; ++i) {
//        //遍历数组的每一个`索引`（不包括最后一个,因为比较的是j+1）
//        for (int j = 0; j < self.arrData.count-1; ++j) {
//            //根据索引的`相邻两位`进行`比较`
//            SKProduct *productj = self.arrData[j];
//            SKProduct *productj1 = self.arrData[j+1];
//            NSComparisonResult result_clearrate_float = [productj.price compare:productj1.price];
//            if (result_clearrate_float == NSOrderedDescending) {
//
//                [self.arrData exchangeObjectAtIndex:j withObjectAtIndex:j+1];
//            }
//
//        }
//    }
    
   
    [self.tableView reloadData];

    
    //    self.titleLab.text =
    
}
- (void)productPurchased:(NSNotification *)notification {
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self hideProgress:self.view animated:YES];
    
    SKPaymentTransaction *transaction = (SKPaymentTransaction *) notification.object;
    NSString *encodeStr = [transaction.transactionReceipt base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    [self receiptWith:encodeStr];
//    [self showProgressWithView:self.view animated:YES];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
//        NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self hideProgress:self.view animated:YES];
//             NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
//            [self receiptWith:receiptString];
//        });
//
//    });
    
    
   

    
    
    
}
-(void)receiptWith:(NSString *)receipt{
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:@{@"receipt":receipt} url:@"pay/iosInAppPurchase" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [weakSelf hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            [weakSelf walletMoney ];
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
    
}

- (void)productPurchaseFailed:(NSNotification *)notification {
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self hideProgress:self.view animated:YES];
    
    SKPaymentTransaction * transaction = (SKPaymentTransaction *) notification.object;
    if (transaction.error.code != SKErrorPaymentCancelled) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                        message:transaction.error.localizedDescription
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK", nil];
        
        [alert show];
    }
    
}

/*
 方法描述:
 加载列表
 
 参数说明:
 <#参数说明#>
 
 返回结果:
 <#返回结果#>
 
 */
-(void)loadTabbleView{
    [self.tableView registerNib:[UINib nibWithNibName:@"TaijieBiTableViewCell" bundle:nil] forCellReuseIdentifier:@"TaijieBiTableViewCell"];
    self.footerView.frame = CGRectMake(0, 0, kScreenWidth, 60);
    self.tableView.tableFooterView = self.footerView;
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}
#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrData.count;
//    [InAppRageIAPHelper sharedHelper].products.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 65;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *identifier = @"TaijieBiTableViewCell";
    TaijieBiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    //    MessageModel *model = self.arrData[indexPath.row];
    //    cell.titleName.text = model.title;
//    SKProduct *product = [self.arrData objectAtIndex:indexPath.row];
//    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
//    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
//    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
//    [numberFormatter setLocale:product.priceLocale];
//    NSString *formattedString = [numberFormatter stringFromNumber:product.price];
//    formattedString = [formattedString stringByReplacingOccurrencesOfString:@".00" withString:@""];
    NSDictionary *dic = self.arrData[indexPath.row];
    cell.taijieLabel.text = [NSString stringWithFormat:@"购买%@个台阶币",dic[@"name"]];
    [cell.priceButton setTitle:[NSString stringWithFormat:@"¥%@",dic[@"price"]] forState:UIControlStateNormal];
    cell.priceButton.tag = indexPath.row;
    [cell.priceButton addTarget:self action:@selector(applePayNow:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}

-(void)applePayNow:(UIButton *)sender{
    [self showProgressWithView:self.view animated:YES];
//    SKProduct *product = [self.arrData objectAtIndex:sender.tag];
    NSDictionary *dic = self.arrData[sender.tag];
    [[InAppRageIAPHelper sharedHelper] buyProductIdentifier:dic[@"id"]];
    
    
    [self performSelector:@selector(timeout:) withObject:nil afterDelay:60];
}
- (void)timeout:(id)arg {
    //    [CommonUtils showToast:@"请求超时,请重试"];
    [self hideProgress:self.view animated:YES];
    
}
- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    
}


- (void)updateInterfaceWithReachability: (Reachability*) curReach {
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)doBack:(id)sender
{
    [super doBack:sender];
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
